package net.maku.utils;

import java.util.Map;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.maku.bean.model.LoginFailException;
import net.maku.bean.model.MyException;
import net.maku.constant.SessionConstant;
import net.maku.entity.WebUserEntity;
 
@Slf4j
public class TokenUtils {

    /**
     * 生成 AccessToken
     */
    public static String generator() {
        return UUID.fastUUID().toString(true);
    }

    /**
     * 获取 AccessToken
     */
    public static TokenHeader getAccessToken(HttpServletRequest request) {
    	String token = ReqUtils.getHeader( request, SessionConstant.AUTHENTICATION, "" );
        if (StrUtil.isBlank(token)) {
        	token = request.getParameter("access_token");
        }
        if (StrUtil.isBlank(token)) {
        	throw new LoginFailException("用户没有传递token");
        }
        log.info("token: " + token);
        String deviceid = ReqUtils.getHeader( request, SessionConstant.DEVICEID, "" );
        if (StrUtil.isBlank(deviceid)) {
        	throw new LoginFailException("用户没有传递deviceid");
        }
        return new TokenHeader(token, deviceid);
    }
    
    
    public static TokenHeader getAccessToken() {
    	ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            return getAccessToken( request );
        }
        throw new LoginFailException("用户没有传递token");
    }
    
    public static Map<String,Object> getUserInfo() {
    	TokenHeader header = getAccessToken();
    	Claims user = NewJwtUtils.parseToken(header.getToken());
    	log.info(user.toString());
    	if( header.getDeviceid().equals(user.getId()) ) {
    		return user;
    	}
    	throw new LoginFailException("用户设备错误，请重新登录");
    }
    
    public static WebUserEntity getUserBean() {
    	try {
        	TokenHeader header = getAccessToken();
        	Claims user = NewJwtUtils.parseToken(header.getToken());
        	log.info(user.toString());
        	WebUserEntity entity = JsonUtils.fromJson(user.get("user").toString(), WebUserEntity.class);
        	entity.setDeviceid(header.getDeviceid());
        	if( header.getDeviceid().equals(user.getId()) ) {
        		return entity;
        	}
        	throw new LoginFailException("用户设备错误，请重新登录");
    	} catch( Throwable ex ) {
    		throw new LoginFailException("用户token异常，请重新登录");
    	}
    }
    
    
}

@Data
@AllArgsConstructor
class TokenHeader{
	String token;
	String deviceid;
}



